/**
 * 表单验证，标识跟提示都在html里面，这里只是逻辑
 * <input type="text" name="task_name" id="task_name" class="form" data-strmax_value="14" data-strmax_notice="不能超过14个字" data-required_notice="请输入任务名称！" />
 * <p class="error"></p>
 * if(_validate($("#ff"))) $("#ff").submit();
 *
 * @author 煤老板 <meok23@sina.com>
 * @date 2015-09-21
 */

/* 表单验证 */
function _validate() {
    var ff = arguments[0];
    var status = true;

    // 1非空验证
    ff.find('[data-required_notice]').each(function (index, element) {
        var obj = $(element);
        var tmp = $.trim(obj.val());
        var notice = '<span class="required_notice">' + obj.data('required_notice') + '</span>';
        if (tmp === '') {
            _validate_notice(obj, notice);
            status = false;
        } else {
            obj.nextAll('.error').find('.required_notice').remove();
        }
    });

    // 2字数最长验证
    ff.find('[data-strmax_notice]').each(function (index, element) {
        var obj = $(element);
        var tmp = $.trim(obj.val());
        var notice = '<span class="strmax_notice">' + obj.data('strmax_notice') + '</span>';
        if (tmp.length > obj.data('strmax_value')) {
            _validate_notice(obj, notice);
            status = false;
        } else {
            obj.nextAll('.error').find('.strmax_notice').remove();
        }
    });
    // 3字数最短验证
    ff.find('[data-strmin_notice]').each(function (index, element) {
        var obj = $(element);
        var tmp = $.trim(obj.val());
        var notice = '<span class="strmin_notice">' + obj.data('strmin_notice') + '</span>';
        if (tmp.length < obj.data('strmin_value')) {
            _validate_notice(obj, notice);
            status = false;
        } else {
            obj.nextAll('.error').find('.strmin_notice').remove();
        }
    });

    // 4最大值验证
    ff.find('[data-max_notice]').each(function (index, element) {
        var obj = $(element);
        var tmp = Number($.trim(obj.val()));
        var notice = '<span class="max_notice">' + obj.data('max_notice') + '</span>';
        if (tmp > obj.data('max_value')) {
            _validate_notice(obj, notice);
            status = false;
        } else {
            obj.nextAll('.error').find('.max_notice').remove();
        }
    });

    // 5最小值验证
    ff.find('[data-min_notice]').each(function (index, element) {
        var obj = $(element);
        var tmp = Number($.trim(obj.val()));
        var notice = '<span class="min_notice">' + obj.data('min_notice') + '</span>';
        if (tmp < obj.data('min_value')) {
            _validate_notice(obj, notice);
            status = false;
        } else {
            obj.nextAll('.error').find('.min_notice').remove();
        }
    });

    return status;
}


/* 表单验证：提示 */
function _validate_notice() {
    var obj = arguments[0];
    var notice = arguments[1];

    if (obj.data('alert')) {
        alert(notice);
    } else {
        obj.nextAll('.error').html(notice);
        obj.focus();
    }
}
